# 测试安全性功能
Write-Host "=== 测试安全性功能 ===" -ForegroundColor Green

# 1. 测试未登录访问受保护资源
Write-Host "`n1. 测试未登录访问受保护资源..." -ForegroundColor Yellow
try {
    $response = Invoke-RestMethod -Uri "http://localhost:5252/api/user/tree" -Method GET
    Write-Host "⚠ 警告：未登录可以访问用户数据" -ForegroundColor Yellow
} catch {
    Write-Host "✓ 未登录无法访问受保护资源" -ForegroundColor Green
}

# 2. 测试登录功能
Write-Host "`n2. 测试登录功能..." -ForegroundColor Yellow
try {
    $loginData = @{
        username = "admin"
        password = "123456"
    } | ConvertTo-Json
    
    $loginResponse = Invoke-RestMethod -Uri "http://localhost:5252/api/auth/login" -Method POST -Body $loginData -ContentType "application/json"
    
    if ($loginResponse.token) {
        Write-Host "✓ 登录成功，获取到token" -ForegroundColor Green
        $token = $loginResponse.token
        
        # 3. 测试使用token访问受保护资源
        Write-Host "`n3. 测试使用token访问受保护资源..." -ForegroundColor Yellow
        try {
            $headers = @{
                "Authorization" = "Bearer $token"
            }
            
            $userResponse = Invoke-RestMethod -Uri "http://localhost:5252/api/user/tree" -Method GET -Headers $headers
            Write-Host "✓ 使用token成功访问受保护资源" -ForegroundColor Green
        } catch {
            Write-Host "✗ 使用token访问失败: $($_.Exception.Message)" -ForegroundColor Red
        }
        
        # 4. 测试token验证
        Write-Host "`n4. 测试token验证..." -ForegroundColor Yellow
        try {
            $validateResponse = Invoke-RestMethod -Uri "http://localhost:5252/api/auth/validate" -Method GET -Headers $headers
            Write-Host "✓ Token验证成功" -ForegroundColor Green
        } catch {
            Write-Host "✗ Token验证失败: $($_.Exception.Message)" -ForegroundColor Red
        }
        
        # 5. 测试登出功能
        Write-Host "`n5. 测试登出功能..." -ForegroundColor Yellow
        try {
            $logoutResponse = Invoke-RestMethod -Uri "http://localhost:5252/api/auth/logout" -Method POST -Headers $headers
            Write-Host "✓ 登出成功" -ForegroundColor Green
        } catch {
            Write-Host "✗ 登出失败: $($_.Exception.Message)" -ForegroundColor Red
        }
        
    } else {
        Write-Host "✗ 登录失败，未获取到token" -ForegroundColor Red
    }
} catch {
    Write-Host "✗ 登录测试失败: $($_.Exception.Message)" -ForegroundColor Red
}

Write-Host "`n=== 安全性测试完成 ===" -ForegroundColor Green
Write-Host "`n建议检查项目：" -ForegroundColor Cyan
Write-Host "1. 前端路由守卫是否正常工作" -ForegroundColor White
Write-Host "2. Token是否在请求头中正确传递" -ForegroundColor White
Write-Host "3. 后端API是否正确验证token" -ForegroundColor White
Write-Host "4. 登出后token是否被正确清除" -ForegroundColor White 